/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Description: Output.
 * Version: 1.0.0.4, Jun 9, 2010
 * Author: Liang Ding
 */

$(function(){
    output.init();
});

output = {
    socket: undefined,
    clear: function() {
        $("#output").html("");
    },
    appendHtml: function(html) {
        var origHtml = this.getHtml();
        this.setHtml(origHtml + html + "<br/>");

        document.getElementById("output").scrollTop =
        document.getElementById("output").scrollHeight;
    },
    appendText: function(text) {
        var origText = this.getText();
        this.setText(origText + text);
        
        document.getElementById("output").scrollTop =
        document.getElementById("output").scrollHeight;
    },
    setHtml: function(html) {
        $("#output").html(html);
    },
    getHtml: function() {
        return $("#output").html();
    },
    setText: function(text) {
        $("#output").text(text);
    },
    getText: function() {
        return $("#output").text();
    },
    init: function() {
        this.clear();

        var url = document.location.toString().replace("http:","ws:");
        url = url.replace("index", "output");
        var outputSocket = new WebSocket(url);

        this.socket = outputSocket;
        
        outputSocket.onmessage = function(evt) {
            output.appendHtml(evt.data);
        };

        outputSocket.onclose = function() {
            output.clear();
            output.setHtml("<span style='color: red;'>Output connection closed!</span>")
        };

        outputSocket.onopen = function() {
            var data = {
                "webSocketGreeting": "Hello server, I am output."
            };

            this.send(JSON.stringify(data));

            window.setInterval(function() {
                keepAlive(output.socket, data);
            }, 10000);
        };
    }
}


